package com.vst.serverdatalib;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.vst.serverdatalib.entity.ChannelAndWeekMap;
import com.vst.serverdatalib.entity.HonorUser;
import com.vst.serverdatalib.entity.HotChannel;
import com.vst.serverdatalib.entity.LiveSubcribe;
import com.vst.serverdatalib.entity.ServerConfigEntity;
import com.vst.serverdatalib.entity.UrlRequestEntity;
import com.vst.serverdatalib.entity.V2TVBack;
import com.vst.serverdatalib.https.BASE64Util;
import com.vst.serverdatalib.https.HttpHelper;
import com.vst.serverdatalib.https.LogUtil;

public class ServerDataHelper {
    private static final String TAG = "ServerDataHelper";

    static String getJsonContent(Context context, Object Key) {
        return getJsonContent(context, Key, null);
    }

    static String getJsonContent(Context context, Object Key, ArrayList<NameValuePair> pairs) {
        ServerConfigEntity serverConfigEntity = ServerConfigEntity.getInstance(context);
        return HttpHelper.getJsonContent(pairs, serverConfigEntity.getMapUrlRequestEntitys().get(Key),
                serverConfigEntity.getMapUrlRequestEntitys().get(ServerConfigEntity.KEY_DEFUALT));
    }

    private static boolean getJsonContentFromNet(Context context, ServerConfigEntity serverEntity) {
        boolean isUpdate = false;
        String configPath;
        String jsonContent;
        int major = serverEntity.getVersion_major();
        int conf = serverEntity.getVersion_conf();
        UrlRequestEntity urlDefaultEntity = serverEntity.getMapUrlRequestEntitys().get(ServerConfigEntity.KEY_DEFUALT);
        jsonContent = getServerJson(serverEntity, major, conf, urlDefaultEntity, ServerConfigEntity.KEY_SERVER1);
        if (TextUtils.isEmpty(jsonContent)) {
            jsonContent = getServerJson(serverEntity, major, conf, urlDefaultEntity, ServerConfigEntity.KEY_SERVER2);
            if (TextUtils.isEmpty(jsonContent)) {
                jsonContent = getServerJson(serverEntity, major, conf, urlDefaultEntity, ServerConfigEntity.KEY_SERVER3);
                if (TextUtils.isEmpty(jsonContent)) {
                    jsonContent = getServerJson(serverEntity, major, conf, urlDefaultEntity,
                            ServerConfigEntity.KEY_SERVER4);
                    if (TextUtils.isEmpty(jsonContent)) {
                        jsonContent = getServerJson(serverEntity, major, conf, urlDefaultEntity,
                                ServerConfigEntity.KEY_SERVER5);
                        if (TextUtils.isEmpty(jsonContent)) {
                            major = -1;
                            conf = -1;
                            for (int i = 0; i < Constans.sReserveUrls.size(); i++) {
                                configPath = BASE64Util.decryptBASE64(Constans.sReserveUrls.get(i)) + "?major=-1&conf_ver=-1";
                                LogUtil.i(TAG, "configPath=" + configPath);
                                jsonContent = HttpHelper.getJsonContent(configPath);
                                LogUtil.i(TAG, "jsonContent=" + jsonContent);
                                if (!TextUtils.isEmpty(jsonContent)) {// 如果不为空，则说明下载成，则直接结束当前循环
                                    SharedPreHelper.saveServerConfigContent(context, jsonContent);
                                    isUpdate = true;
                                    break;
                                } else {
                                    isUpdate = false;
                                }
                            }
                        } else {
                            SharedPreHelper.saveServerConfigContent(context, jsonContent);
                            return true;
                        }
                    } else {
                        SharedPreHelper.saveServerConfigContent(context, jsonContent);
                        return true;
                    }
                } else {
                    SharedPreHelper.saveServerConfigContent(context, jsonContent);
                    return true;
                }
            } else {
                SharedPreHelper.saveServerConfigContent(context, jsonContent);
                return true;
            }
        } else {
            SharedPreHelper.saveServerConfigContent(context, jsonContent);
            return true;
        }
        return isUpdate;
    }

    private static String getServerJson(ServerConfigEntity serverEntity, int major, int conf,
            UrlRequestEntity urlDefaultEntity, String key) {
        String configPath;
        String jsonContent;
        UrlRequestEntity entitiy;
        entitiy = serverEntity.getMapUrlRequestEntitys().get(key);
        configPath = getJsonString(entitiy.getUrl()) + "?major=" + major + "&conf_ver=" + conf;
        LogUtil.i(TAG, "configPath=" + configPath);
        jsonContent = HttpHelper.getJsonContent(entitiy, urlDefaultEntity, configPath);
        LogUtil.i(TAG, "jsonContent=" + jsonContent);
        return jsonContent;
    }

    private static String getJsonString(String url) {
        if (TextUtils.isEmpty(url)) {
            return url;
        }
        if (url.endsWith(".json")) {
            return url;
        }
        return url + ".json";
    }

    public static boolean updateServerConfig(Context context) {
        // 先从默认地址取配置文件
        String configPath = Constans.DEFAULT_SERVER_CONFIG_PATH + "?major=-1&conf_ver=-1";
        LogUtil.i(TAG, "configPath=" + configPath);
        String jsonContent = HttpHelper.getJsonContent(configPath);
        LogUtil.i(TAG, "jsonContent=" + jsonContent);
        if (TextUtils.isEmpty(jsonContent)) {// 如果获取失败，则从本地的保存的配置文件或者上次更新的文件中获取
            return getJsonContentFromNet(context, ServerConfigEntity.getInstance(context));
        } else {
            SharedPreHelper.saveServerConfigContent(context, jsonContent);// 下载成功
            return true;
        }
    }

    public static InputStream getHomePageConfigInputStream(Context context, String channel, String apkVersion,
            String machinename) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("channel", Uri.encode(channel, HTTP.UTF_8)));
        pairs.add(new BasicNameValuePair("apkversion", apkVersion));
        pairs.add(new BasicNameValuePair("machinename", Uri.encode(machinename, HTTP.UTF_8)));
        ServerConfigEntity serverConfigEntity = ServerConfigEntity.getInstance(context);
        HttpEntity httpEntity = HttpHelper.getHttpEntity(pairs,
                serverConfigEntity.getMapUrlRequestEntitys().get(ServerConfigEntity.KEY_HOME_PAGE), serverConfigEntity
                        .getMapUrlRequestEntitys().get(ServerConfigEntity.KEY_DEFUALT));
        if (httpEntity != null) {
            LogUtil.i(TAG, "getHomePageConfigInputStream=" + httpEntity.getContentLength());
        }
        return HttpHelper.getStream(httpEntity);
    }

    public static void saveVodConfigHtml(Context context) {
        savePlayConfigHtml(context, false, true);
    }

    public static void saveLiveConfigHtml(Context ctx) {
        savePlayConfigHtml(ctx, true, false);
    }

    public static void savePlayConfigHtml(Context context, boolean isLoadLiveConfig, boolean isLoadVodConfig) {
        ServerConfigEntity entity = ServerConfigEntity.getInstance(context);
        if (entity == null) {
            return;
        }
        // String livePlay = entity.mServer_live_play;
        // String vodPlay = entity.mServer_vod_play;
        // String vodFile = "";
        // String liveFile = "";
        // if (isLoadLiveConfig && !TextUtils.isEmpty(livePlay)) {
        // liveFile = HttpHelper.getJsonContent(livePlay);
        // LogUtil.i(TAG, "liveFile = " + liveFile);
        // }
        // if (isLoadVodConfig && !TextUtils.isEmpty(vodPlay)) {
        // vodFile = HttpHelper.getJsonContent(vodPlay);
        // LogUtil.i(TAG, "vodFile = " + vodFile);
        // }
        // FileUtil.WriteString2File(Constans.VOD_PLAY_COFING_FILE_NAME,
        // vodFile, context);
        // FileUtil.WriteString2File(Constans.LIVE_PLAY_COFING_FILE_NAME,
        // liveFile, context);
    }

    public static String getVodPlayConfigFileSavePath(Context context) {
        return FileUtil.getExternalStoragePath(context) + FileUtil.JSONCACHE + "/" + Constans.VOD_PLAY_COFING_FILE_NAME;
    }

    public static String getLivePlayConfigFileSavePath(Context context) {
        return FileUtil.getExternalStoragePath(context) + FileUtil.JSONCACHE + "/"
                + Constans.LIVE_PLAY_COFING_FILE_NAME;
    }

    public static int getLiveDataVersion(Context context) {
        String json = getJsonContent(context, ServerConfigEntity.KEY_LIVE_DATE_VERSION);
        LogUtil.i(TAG, "getLiveDataVersion=" + json);
        if (TextUtils.isEmpty(json)) {
            return -1;
        }
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.optInt("verTime");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static List<HotChannel> getHotChannelList(Context context) {
        String json = getJsonContent(context, ServerConfigEntity.KEY_HOT_CHANNELS);
        LogUtil.i(TAG, "getHotChannelList=" + json);
        if (TextUtils.isEmpty(json)) {
            return Collections.emptyList();
        }
        List<HotChannel> channels = new ArrayList<HotChannel>();
        try {
            JSONObject object = new JSONObject(json);
            JSONArray jsonArray = object.optJSONArray("list");
            HotChannel channel;
            for (int i = 0; i < jsonArray.length(); i++) {
                channel = new HotChannel(jsonArray.opt(i).toString());
                channels.add(channel);
            }
            return channels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    public static ChannelAndWeekMap getChannelAndWeekMap(Context context) {
        String json = getJsonContent(context, ServerConfigEntity.KEY_LIVE_BACK_V1);
        LogUtil.i(TAG, "ChannelAndWeekMap=" + json);
        return new ChannelAndWeekMap(json);
    }

    public static V2TVBack getV2TVBackInfo(Context context, String channelId) {
        ServerConfigEntity serverConfigEntity = ServerConfigEntity.getInstance(context);
        UrlRequestEntity entity = serverConfigEntity.getMapUrlRequestEntitys().get(ServerConfigEntity.KEY_LIVE_BACK_V2);
        UrlRequestEntity defaultEntity = serverConfigEntity.getMapUrlRequestEntitys().get(
                ServerConfigEntity.KEY_DEFUALT);
        if (entity != null && defaultEntity != null && !TextUtils.isEmpty(entity.getUrl())) {
            String json = HttpHelper.getJsonContent(entity.getUrl() + channelId + ".json",
                    HttpHelper.getHeaders(entity, defaultEntity), entity.getQuestMethod());
            LogUtil.i(TAG, "getV2TVBackInfo=" + json);
            return new V2TVBack(json);
        }
        return null;
    }

    public static ArrayList<LiveSubcribe> getLiveSubCribeList(Context context) {
        ArrayList<LiveSubcribe> sublist = new ArrayList<LiveSubcribe>();
        String json = getJsonContent(context, ServerConfigEntity.KEY_LIVE_SUBSCRIBE);
        try {
            LogUtil.i(TAG, "getLiveSubCribe=" + json);
            LiveSubcribe liveSubcribe;
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                liveSubcribe = new LiveSubcribe(jsonArray.opt(i).toString());
                sublist.add(liveSubcribe);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sublist;
    }

    public static ArrayList<HonorUser> getHonorRanking(Context context) {
        ArrayList<HonorUser> honorUsers = new ArrayList<HonorUser>();
        String json = getJsonContent(context, ServerConfigEntity.KEY_LIVE_SUBSCRIBE);
        try {
            LogUtil.i(TAG, "getLiveSubCribe=" + json);
            HonorUser honorUser;
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                honorUser = new HonorUser(jsonArray.opt(i).toString());
                honorUsers.add(honorUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return honorUsers;
    }
}
